package main

import (
	"github.com/astaxie/beego"
	gk "github.com/moovweb/gokogiri"
	css "github.com/moovweb/gokogiri/css"
	"log"
	"strings"
	//"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	beego.Router("/", new(MainController))
	beego.Router("/hello", new(MainController), "get:Index")
	beego.Router("/baidu", new(MainController), "get:Baidu")

	log.Println("Listen at 0.0.0.0:8080")
	beego.Run()
}

type MainController struct {
	beego.Controller
}

func (c *MainController) Get() {
	c.Ctx.WriteString("hello World!")
}

func (c *MainController) Index() {
	c.Ctx.WriteString("Hello Index World!")
}

func (c *MainController) Baidu() {
	links := ExtraBaidu()
	log.Println(links)
	c.Ctx.ContentType("html")
	c.Ctx.WriteString(strings.Join(links, "<br>"))
}

func ExtraBaidu() []string {
	resp, _ := http.Get("http://www.baidu.com")
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	doc, err := gk.ParseHtml(body)
	defer doc.Free()
	if err != nil {
		log.Fatal("Have error", err)
	}
	html := doc.Root()
	//links, _ := html.Search("//a")
	//links, _ := html.Search(css.Convert("a", css.GLOBAL))
	links, _ := html.Search(css.Convert("a", css.LOCAL))
	linkStrs := []string{}
	for _, link := range links {
		//append(linkStrs, link.Path() + link.Attr("href") + link.Content())
		linkStrs = append(linkStrs, link.String())
	}
	return linkStrs
}
